package com.tz;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.service.wallpaper.WallpaperService.Engine;
import android.util.Log;
import android.view.SurfaceHolder;

public class GameOfLifeWallpaper extends WallpaperService {

  @Override
  public Engine onCreateEngine() {
    return new GameOfLifeEngine();
  }
  
  class GameOfLifeEngine extends Engine {
    
    GameOfLifeEngine() {
      final Paint paint = paint_;
      paint.setColor(0xffffffff);
      paint.setAntiAlias(true);
      paint.setStrokeWidth(2);
      paint.setStrokeCap(Paint.Cap.ROUND);
      paint.setStyle(Paint.Style.STROKE);
    }
    
    void DrawFrame() {
      Log.i("DrawFrame", "draw");
      final SurfaceHolder holder = getSurfaceHolder();

      Canvas c = null;
      try {
          c = holder.lockCanvas();
          if (c != null) {
            // draw something
            c.drawLine(0, 0, 100, 100, paint_);
          }
      } finally {
          if (c != null) holder.unlockCanvasAndPost(c);
      }

      // Reschedule the next redraw
      handler_.removeCallbacks(drawer_);
      if (visible_) {
        handler_.postDelayed(drawer_, 1000 / 25);
      }      
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        handler_.removeCallbacks(drawer_);
    }

    @Override
    public void onVisibilityChanged(boolean visible) {
        visible_ = visible;
        if (visible) {
            DrawFrame();
        } else {
          handler_.removeCallbacks(drawer_);
        }
    }
    
    private final Paint paint_ = new Paint();
    private final Runnable drawer_ = new Runnable() {
      public void run() {
        DrawFrame();
      }
    };
    private boolean visible_ = true;
  }  // GameOfLifeEngine

  private final Handler handler_ = new Handler();
}
